CC        := g++
LD        := g++
UNAME     := $(shell uname)

MODULES   := domain domain/temperaturescale exceptions output ui ui/plots util
LIBS      := cmpfit-1.2
SRC_DIR   := $(addprefix src/,$(MODULES))
BUILD_DIR := $(addprefix build/,$(MODULES))
LIB_DIR   := $(addprefix lib/,$(LIBS))

APPNAME   := tltgen
BUNDLE    := build/$(APPNAME).app
BUNDLESIG := PDJA
MACOSXDIR := MacOSX

SRC       := $(foreach sdir,$(SRC_DIR),$(wildcard $(sdir)/*.cpp))
OBJ       := $(patsubst src/%.cpp,build/%.o,$(SRC))
INCLUDES  := -I/opt/local/include -Isrc $(addprefix -I,$(SRC_DIR)) $(addprefix -I,$(LIB_DIR))
LIB_INCL  := $(addprefix -L,$(LIB_DIR))

CFLAGS    := -g -Wall `wx-config --cxxflags` `pkg-config --cflags plplotd`
LDFLAGS   := $(LIB_INCL) -lmpfit -lgsl -lgslcblas -lm -lboost_regex-mt -lboost_signals-mt -lboost_serialization-mt `wx-config --libs core,base,aui,adv,qa` `pkg-config --libs plplotd-wxwidgets`

vpath %.cpp $(SRC_DIR)

define make-goal
$1/%.o: %.cpp
	$(CC) $(INCLUDES) $(CFLAGS) -c $$< -o $$@
endef

.PHONY: all checkdirs clean

all: $(BUNDLE)

build/$(APPNAME): checkdirs $(OBJ) lib/cmpfit-1.2/libmpfit.a
	$(LD) $(OBJ) $(LDFLAGS) -o $@

$(BUNDLE): build/$(APPNAME) $(MACOSXDIR)/Info.plist $(MACOSXDIR)/PkgInfo $(MACOSXDIR)/$(APPNAME).icns
	@echo " Building: $(BUNDLE)"
	mkdir -p $(BUNDLE)/Contents
	mkdir -p $(BUNDLE)/Contents/MacOS
	mkdir -p $(BUNDLE)/Contents/Resources
	cp $(MACOSXDIR)/Info.plist $(BUNDLE)/Contents/Info.plist
	cp $(MACOSXDIR)/PkgInfo $(BUNDLE)/Contents/PkgInfo
	cp build/$(APPNAME) $(BUNDLE)/Contents/MacOS/
#	cp -f $(MACOSXDIR)/$(APPNAME).icns $(BUNDLE)/Contents/Resources/

checkdirs: $(BUILD_DIR)

$(BUILD_DIR):
	@mkdir -p $@

lib/cmpfit-1.2/libmpfit.a:
	$(MAKE) -C lib/cmpfit-1.2

clean:
	@rm -rf $(BUILD_DIR)

$(foreach bdir,$(BUILD_DIR),$(eval $(call make-goal,$(bdir))))
